DECLARE @USER VARCHAR(25)

DECLARE CUR_USER CURSOR FOR
	SELECT RTRIM(USUARIO) FROM USERS WHERE USUARIO<>'SA'

OPEN CUR_USER
FETCH NEXT FROM CUR_USER INTO @USER

WHILE @@FETCH_STATUS=0
BEGIN
	IF NOT EXISTS(SELECT * FROM MASTER..SYSLOGINS WHERE NAME = @USER)
		EXEC('	USE MASTER
		 	EXEC sp_addlogin '''+@USER+'''')

	IF EXISTS(SELECT * FROM SYSUSERS WHERE NAME = @USER)
		EXEC SP_DROPUSER @USER

	EXEC sp_adduser @USER, @USER, 'PUBLIC'

	FETCH NEXT FROM CUR_USER INTO @USER
END
CLOSE CUR_USER
DEALLOCATE CUR_USER
GO


declare @tabela varchar(100)

set nocount on

create table #groups (Group_name VARCHAR(50),Group_id SMALLINT)

INSERT INTO #Groups
	EXEC('sp_helpgroup')

declare cur_tabelas scroll cursor for
select '['+RTRIM(name)+']' from sysobjects where type in ('U', 'V', 'P') and uid=1 order by name

open cur_tabelas
fetch next from cur_tabelas into @tabela

while @@fetch_status <> -1
begin
	IF EXISTS(SELECT * FROM #Groups WHERE Group_Name='public')
	exec('grant all on ' + @tabela + ' to public')
	IF EXISTS(SELECT * FROM #Groups WHERE Group_Name='dbas')
	exec('grant all on ' + @tabela + ' to dbas')
	fetch next from cur_tabelas into @tabela	
end

close cur_tabelas
deallocate cur_tabelas			
DROP TABLE #Groups
set nocount off
go